import Logger from "../utils/Logger"
import SegmentBootstrap from "../utils/SegmentBootstrap"
import analyticsEnum from "../enum/analytics.enum"
const logger = new Logger("segment")
declare global {
  interface Window {
    analytics: any
  }
}
export default class SegmentAnalyticsProvider {
  token: string
  endpointType: string
  options: any
  context: any
  constructor(token?: string) {
    this.token = token
    this.endpointType = analyticsEnum.Segment
  }
  init(options: any, context: any) {
    this.options = options
    this.context = context
    if (this.token) {
      window.analytics && window.analytics.initialize && (window.analytics = null)
      window.analytics || SegmentBootstrap()
      window.analytics.load(this.token)
      return new Promise(resolve => {
        window.analytics.ready(resolve)
      })
    } else {
      return Promise.resolve()
    }
  }
  identify(e: { id: any; firstName: any; lastName: any; email: any }) {
    window.analytics.identify(e.id, {
      first_name: e.firstName,
      last_name: e.lastName,
      email: e.email
    })
  }
  track(e: any, t: any) {
    Logger.level >= 3 && logger.debug(e, t ? JSON.stringify(t).replace('\\"', '"') : t), (t = Object.assign(t || {}, this.options))
    try {
      window.analytics.track(e, t, this.context)
    } catch (t) {
      logger.error(`Failed to send data to segment for ${e}`)
    }
  }
  trackAsync(e: any, t: {}) {
    if (((t = t || {}), navigator.sendBeacon))
      try {
        navigator.sendBeacon(
          "https://api.segment.io/v1/t",
          JSON.stringify({
            event: e,
            anonymousId: window.analytics.user().anonymousId(),
            properties: Object.assign({ data: t }, this.options),
            writeKey: this.token,
            sentAt: Date.now(),
            type: "track",
            context: this.context
          })
        )
      } catch (e) {
        logger.error("Failed to send async segment request")
      }
  }
}
